/*
 * jxSwing Project (2015)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2015
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxSwing.component.dialog;

import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.Window;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

import org.jxSwing.i18n.I18N;

/**
 * @author Denilson Edinaldo Pinto
 * @porject jxSwing
 * @package org.jxSwing.component.dialog
 * @date 10/01/2015 - 15:34:08
 */
public abstract class WaitDialog<T> {
	
	private T result;
	
	/**
	 * 
	 */
	public WaitDialog() {
	
		this(null);
	}
	
	/**
	 * @param owner
	 */
	public WaitDialog(final Window owner) {
	
		this(owner, I18N.component().pleaseWait());
	}
	
	/**
	 * @param owner
	 * @param message
	 */
	public WaitDialog(final Window owner, final String message) {
	
		final JDialog dialog = new JDialog(owner, message, ModalityType.APPLICATION_MODAL);
		
		final JLabel lblMessage = new JLabel(message);
		
		lblMessage.setHorizontalAlignment(JLabel.CENTER);
		
		final JProgressBar progressBar = new JProgressBar();
		
		progressBar.setIndeterminate(true);
		
		dialog.setUndecorated(true);
		dialog.add(BorderLayout.CENTER, lblMessage);
		dialog.add(BorderLayout.SOUTH, progressBar);
		dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		dialog.setSize(300, 50);
		dialog.setLocationRelativeTo(null);
		
		final SwingWorker<Void, Void> swingWorker = new SwingWorker<Void, Void>() {
			
			@Override
			protected Void doInBackground() throws Exception {
			
				result = waitWhileThisIsBeingDone();
				
				return null;
			}
			
			@Override
			protected void done() {
			
				dialog.dispose();
			}
		};
		
		swingWorker.execute();
		dialog.setVisible(true);
	}
	
	/**
	 * @return the result to {@link #waitWhileThisIsBeingDone()}
	 */
	public final T getResult() {
	
		return result;
	}
	
	/**
	 * 
	 */
	protected abstract T waitWhileThisIsBeingDone();
}
